package com.lfy.yunpicture.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lfy.yunpicture.annotation.AuthCheck;
import com.lfy.yunpicture.common.BaseResponse;
import com.lfy.yunpicture.common.DeleteRequest;
import com.lfy.yunpicture.common.ErrorCode;
import com.lfy.yunpicture.common.ResultUtils;
import com.lfy.yunpicture.constant.UserConstant;
import com.lfy.yunpicture.exception.BusinessException;
import com.lfy.yunpicture.exception.ThrowUtils;
import com.lfy.yunpicture.manager.auth.annotate.SaSpaceCheckPermission;
import com.lfy.yunpicture.manager.auth.model.SpaceUserPermissionConstant;
import com.lfy.yunpicture.model.dto.space.SpaceAddRequest;
import com.lfy.yunpicture.model.dto.space.SpaceEditRequest;
import com.lfy.yunpicture.model.dto.space.SpaceQueryRequest;
import com.lfy.yunpicture.model.dto.space.SpaceUpdateRequest;
import com.lfy.yunpicture.model.entity.Space;
import com.lfy.yunpicture.model.entity.User;
import com.lfy.yunpicture.model.enums.SpaceLeaveEnum;
import com.lfy.yunpicture.model.vo.SpaceLeave;
import com.lfy.yunpicture.model.vo.SpaceVO;
import com.lfy.yunpicture.service.SpaceService;
import com.lfy.yunpicture.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * 空间接口
 *
*/
@RestController
@RequestMapping("/space")
@Slf4j
public class SpaceController {

    @Resource
    private SpaceService spaceService;

    @Resource
    private UserService userService;

    // region 增删改查

    /**
     * 创建空间
     *
     * @param spaceAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addSpace(@RequestBody SpaceAddRequest spaceAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(spaceAddRequest == null, ErrorCode.PARAMS_ERROR);
        Long spaceId = spaceService.addSpace(spaceAddRequest, request);
        return ResultUtils.success(spaceId);
    }

    /**
     * 删除空间
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteSpace(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean b = spaceService.deleteSpace(deleteRequest.getId(), request);
        return ResultUtils.success(b);
    }
    /**
     * 更新空间（仅管理员可用）
     *
     * @param spaceUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateSpace(@RequestBody SpaceUpdateRequest spaceUpdateRequest) {
        if (spaceUpdateRequest == null || spaceUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //在此处将实体类和 DTO 进行转换
        Space space = new Space();
        BeanUtils.copyProperties(spaceUpdateRequest, space);
        // 根据空间级别获取枚举值
        SpaceLeaveEnum enumBySpaceLeave = SpaceLeaveEnum.getEnumBySpaceLeave(spaceUpdateRequest.getSpaceLevel());
        ThrowUtils.throwIf(enumBySpaceLeave == null , ErrorCode.PARAMS_ERROR ,"不存在该级别的空间" );
        space.setMaxSize(enumBySpaceLeave.getMaxSize());
        space.setMaxCount(enumBySpaceLeave.getMaxCount());
        // 数据校验
        spaceService.validSpace(space, false);
        // 判断是否存在
        long id = spaceUpdateRequest.getId();
        Space oldSpace = spaceService.getById(id);
        ThrowUtils.throwIf(oldSpace == null, ErrorCode.NOT_FOUND_ERROR);
        // 操作数据库
        boolean result = spaceService.updateById(space);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 根据 id 获取空间（封装类）
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_VIEW)
    public BaseResponse<SpaceVO> getSpaceVOById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Space space = spaceService.getById(id);
        ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取封装类
        return ResultUtils.success(spaceService.getSpaceVO(space, request));
    }

    /**
     * 分页获取空间列表（仅管理员可用）
     *
     * @param spaceQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Space>> listSpaceByPage(@RequestBody SpaceQueryRequest spaceQueryRequest) {
        long current = spaceQueryRequest.getCurrent();
        long size = spaceQueryRequest.getPageSize();
        // 查询数据库
        Page<Space> spacePage = spaceService.page(new Page<>(current, size),
                spaceService.getQueryWrapper(spaceQueryRequest));
        return ResultUtils.success(spacePage);
    }

    /**
     * 分页获取空间列表（封装类）
     *
     * @param spaceQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<SpaceVO>> listSpaceVOByPage(@RequestBody SpaceQueryRequest spaceQueryRequest,
                                                               HttpServletRequest request) {
        long current = spaceQueryRequest.getCurrent();
        long size = spaceQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<Space> spacePage = spaceService.page(new Page<>(current, size),
                spaceService.getQueryWrapper(spaceQueryRequest));
        // 获取封装类
        return ResultUtils.success(spaceService.getSpaceVOPage(spacePage, request));
    }

    /**
     * 分页获取当前登录用户创建的空间列表
     *
     * @param spaceQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<SpaceVO>> listMySpaceVOByPage(@RequestBody SpaceQueryRequest spaceQueryRequest,
                                                                 HttpServletRequest request) {
        ThrowUtils.throwIf(spaceQueryRequest == null, ErrorCode.PARAMS_ERROR);
        // 补充查询条件，只查询当前登录用户的数据
        User loginUser = userService.getLoginUser(request);
        spaceQueryRequest.setUserId(loginUser.getId());
        long current = spaceQueryRequest.getCurrent();
        long size = spaceQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<Space> spacePage = spaceService.page(new Page<>(current, size),
                spaceService.getQueryWrapper(spaceQueryRequest));
        // 获取封装类
        return ResultUtils.success(spaceService.getSpaceVOPage(spacePage, request));
    }
    /**
     * 获取登录用户加入的空间列表（封装类）
     */
    @GetMapping("/my/list/vo")
    public BaseResponse<List<SpaceVO>> listMySpaceVO(HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        List<SpaceVO> spaceVOList = spaceService.listMySpaceVO(loginUser);
        return ResultUtils.success(spaceVOList);
    }
    /**
     * 编辑空间（给用户使用）
     *
     * @param spaceEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editSpace(@RequestBody SpaceEditRequest spaceEditRequest, HttpServletRequest request) {
        if (spaceEditRequest == null || spaceEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 在此处将实体类和 DTO 进行转换
        Space space = new Space();
        BeanUtils.copyProperties(spaceEditRequest, space);
        // 数据校验
        spaceService.validSpace(space, false);
        User loginUser = userService.getLoginUser(request);
        SpaceLeaveEnum enumBySpaceLeave = SpaceLeaveEnum.getEnumBySpaceLeave(spaceEditRequest.getSpaceLevel());
        ThrowUtils.throwIf(enumBySpaceLeave == null , ErrorCode.PARAMS_ERROR ,"不存在该级别的空间" );
        // 如果不是管理员，那么只能创建普通空间
        if(!userService.isAdmin(request)){
            ThrowUtils.throwIf(enumBySpaceLeave != SpaceLeaveEnum.COMMON , ErrorCode.NO_AUTH_ERROR ,"非管理员不能创建非普通空间");
        }
        space.setMaxSize(enumBySpaceLeave.getMaxSize());
        space.setMaxCount(enumBySpaceLeave.getMaxCount());
        // 判断是否存在
        long id = spaceEditRequest.getId();
        Space oldSpace = spaceService.getById(id);
        ThrowUtils.throwIf(oldSpace == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldSpace.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = spaceService.updateById(space);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }
    /**
     * 获取空间级别详情
     */
    @GetMapping("/get/spaceLevel")
    public BaseResponse<List<SpaceLeave>> getSpaceLevel(){
        // 遍历空间级别枚举
        List<SpaceLeave> spaceLeaves = new ArrayList<>();
        for(SpaceLeaveEnum spaceLeaveEnum : SpaceLeaveEnum.values()){
            spaceLeaves.add(new SpaceLeave(spaceLeaveEnum.getSpaceLeave(),spaceLeaveEnum.getSpaceName(),spaceLeaveEnum.getMaxSize(),spaceLeaveEnum.getMaxCount()));
        }
        return ResultUtils.success(spaceLeaves);
    }
    // endregion
}
